package com.agent.payment.service;

import com.agent.payment.config.PaymentGatewayConfig;
import com.agent.payment.entity.PaymentOrder;
import com.agent.common.exception.PaymentException;
import com.agent.common.result.ResultCode;
import com.agent.common.utils.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * PayPal支付服务
 * @author Jeff_Wan
 * @description 处理PayPal支付网关的集成逻辑
 */
@Service
@RequiredArgsConstructor
public class PaypalService {
    private final PaymentGatewayConfig paymentGatewayConfig;
    private final ObjectMapper objectMapper;
    
    /**
     * 创建PayPal支付请求
     * @param order 支付订单
     * @return 支付请求URL
     */
    public String createPaymentRequest(PaymentOrder order) {
        // 从配置中获取参数
        PaymentGatewayConfig.PaypalConfig config = paymentGatewayConfig.getPaypal();
        
        // 获取访问令牌
        String accessToken = getPayPalAccessToken(config.getClientId(), config.getClientSecret());

        // 创建支付请求
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("intent", "CAPTURE");

        Map<String, Object> amountMap = new HashMap<>();
        amountMap.put("currency_code", order.getCurrency());
        amountMap.put("value", order.getAmount().toString());

        Map<String, Object> purchaseUnit = new HashMap<>();
        purchaseUnit.put("amount", amountMap);
        purchaseUnit.put("reference_id", order.getOrderNumber());

        requestBody.put("purchase_units", new Map[]{purchaseUnit});

        Map<String, String> appContext = new HashMap<>();
        appContext.put("return_url", config.getReturnUrl());
        appContext.put("cancel_url", config.getCancelUrl());
        requestBody.put("application_context", appContext);

        try {
            String requestBodyJson = objectMapper.writeValueAsString(requestBody);
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + accessToken);
            headers.put("Content-Type", "application/json");

            String response = HttpUtil.post(
                    "https://api-m.paypal.com/v2/checkout/orders",
                    requestBodyJson,
                    headers
            );

            JsonNode responseJson = objectMapper.readTree(response);
            if (responseJson.has("id")) {
                // 查找approve链接
                for (JsonNode link : responseJson.get("links")) {
                    if ("approve".equals(link.get("rel").asText())) {
                        return link.get("href").asText();
                    }
                }
            }
            throw new PaymentException(ResultCode.PAYMENT_GATEWAY_ERROR, "Failed to create PayPal order");
        } catch (Exception e) {
            throw new PaymentException(ResultCode.PAYMENT_GATEWAY_ERROR, "PayPal API error: " + e.getMessage());
        }
    }
    
    /**
     * 验证PayPal回调签名
     * @param callbackData 回调数据
     * @param signature 签名
     * @return 是否验证通过
     */
    public boolean verifyCallback(String callbackData, String signature) {
        PaymentGatewayConfig.PaypalConfig config = paymentGatewayConfig.getPaypal();
        String accessToken = getPayPalAccessToken(config.getClientId(), config.getClientSecret());
        
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + accessToken);
            headers.put("Content-Type", "application/json");
            
            Map<String, String> verifyBody = new HashMap<>();
            verifyBody.put("transmission_id", callbackData.substring(0, 36));
            verifyBody.put("transmission_time", callbackData.substring(37, 65));
            verifyBody.put("cert_url", callbackData.substring(66, 150));
            verifyBody.put("auth_algo", "SHA256withRSA");
            verifyBody.put("transmission_sig", signature);
            verifyBody.put("webhook_id", config.getWebhookId());
            verifyBody.put("webhook_event", callbackData);
            
            String requestBody = objectMapper.writeValueAsString(verifyBody);
            String response = HttpUtil.post(
                "https://api-m.paypal.com/v1/notifications/verify-webhook-signature",
                requestBody,
                headers
            );
            
            JsonNode responseJson = objectMapper.readTree(response);
            return "SUCCESS".equals(responseJson.get("verification_status").asText());
        } catch (Exception e) {
            throw new PaymentException(ResultCode.PAYMENT_GATEWAY_ERROR, "PayPal verification error: " + e.getMessage());
        }
    }
    
    /**
     * 从回调数据中解析订单号
     * @param callbackData 回调数据
     * @return 订单号
     */
    public String parseOrderNumber(String callbackData) {
        try {
            JsonNode event = objectMapper.readTree(callbackData);
            if (event.has("resource") && event.get("resource").has("purchase_units")) {
                JsonNode purchaseUnits = event.get("resource").get("purchase_units");
                if (purchaseUnits.isArray() && purchaseUnits.size() > 0) {
                    return purchaseUnits.get(0).get("reference_id").asText();
                }
            }
            return null;
        } catch (Exception e) {
            throw new PaymentException(ResultCode.PAYMENT_GATEWAY_ERROR, "Failed to parse PayPal callback");
        }
    }
    
    /**
     * 获取PayPal访问令牌
     * @param clientId 客户端ID
     * @param clientSecret 客户端密钥
     * @return 访问令牌
     */
    private String getPayPalAccessToken(String clientId, String clientSecret) {
        try {
            String auth = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
            
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Basic " + auth);
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            
            String response = HttpUtil.post(
                "https://api-m.paypal.com/v1/oauth2/token",
                "grant_type=client_credentials",
                headers
            );
            
            JsonNode responseJson = objectMapper.readTree(response);
            return responseJson.get("access_token").asText();
        } catch (Exception e) {
            throw new PaymentException(ResultCode.PAYMENT_GATEWAY_ERROR, "Failed to get PayPal access token");
        }
    }
}